<template>
  <div class="container">
    <div class="app-container">
      <el-scrollbar>
        <div class="left">
          <el-input
            v-model="queryParams.keyword"
            clearable
            style="margin-bottom:10px"
            type="text"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="输入员工姓名全员搜索"
            @input="search"
            @clear="queryParams.page = 1; getEmployeeList()"
          />
          <!-- 树形组件 -->
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="{ label: 'name' }"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
            node-key="id"
            @node-click="handleClick"
          />
        </div>
      </el-scrollbar>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- <el-button v-if="checkPermission('add')" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-if="checkPermission('importexcel')" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-if="checkPermission('exportexcel')" size="mini" @click="exportEmployee">excel导出</el-button>
           -->
          <el-button :disabled="!checkPermission('add')" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button :disabled="!checkPermission('importexcel')" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button :disabled="!checkPermission('exportexcel')" size="mini" @click="exportEmployee">excel导出</el-button>
          <el-button v-check="'add'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-check="'importexcel'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-check="'exportexcel'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
          <el-table-column label="头像" align="center">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable width="100px" prop="timeOfEntry" />
          <el-table-column label="操作">
            <template #default="o">
              <el-button type="text" @click="$router.push(`/employee/detail/${o.row.id}`)">查看</el-button>
              <el-button type="text" @click="showRoleDialog(o.row.id)">角色</el-button>
              <!-- 气泡弹窗 -->
              <el-popconfirm
                title="确定删除该员工么?"
                @onConfirm="confirm(o.row.id)"
              >
                <template #reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            :current-page="queryParams.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryParams.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 导入子组件 -->
        <ImportExcel :show-excel-dialog.sync="showExcelDialog" @reload="getEmployeeList" />
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="showRoleVisible">
          <!-- 复选框组  v-model收集的是一个数组 -->
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in rolesList"
              :key="item.id"
              :label="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          <div style="text-align: center;">
            <el-button type="primary" size="mini" @click="submit">确定</el-button>
            <el-button size="mini" @click="showRoleVisible = false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import { getDeptList } from '@/api/department'
import { transformToTreedata } from '@/utils'
import { getEmployeeList, exportEmployee, delEmployee, getEmployeeDetail, assignRole } from '@/api/employee'
import { getEnableRolesList } from '@/api/role'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
let timerId
export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      treeData: [],
      // 获取员工列表的查询参数
      queryParams: {
        departmentId: null, // 部门id
        page: 1, // 页码
        pagesize: 5, // 每页条数
        keyword: '' // 搜索的关键词
      },
      tableData: [], // 员工列表
      total: 0, // 员工总数
      showExcelDialog: false,
      showRoleVisible: false,
      checkList: [], // 复选框组收集的数组
      rolesList: [], // 已启用角色列表
      id: ''
    }
  },
  created() {
    this.getDeptList()
  },
  methods: {
    // 按钮操作权限方法
    checkPermission(str) {
      // console.log(this.$store.getters.points)
      return this.$store.getters?.points?.includes(str)
    },
    // 获取部门列表
    async getDeptList() {
      const res = await getDeptList()
      this.treeData = transformToTreedata(res.data, 0)
      // 将默认的总部的部门id赋值给 queryParams.departmentId
      this.queryParams.departmentId = this.treeData[0].id
      // tree组件上的setCurrentKey 可以做默认高亮
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.queryParams.departmentId)
      })
      // 等到departmentId赋值后 再获取员工列表
      this.getEmployeeList()
    },
    // 树形节点被点击的处理函数, 将点击的部门id记录给queryParams.departmentId
    handleClick(data) {
      // console.log(data)
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1
      // 重新获取员工列表
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.queryParams.pagesize = val
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getEmployeeList()
    },
    // 当输入框值修改了发送请求
    search() {
      // 1. 空值的处理
      if (!this.queryParams.keyword.trim()) return
      // 2. 将page 改为1
      this.queryParams.page = 1
      // 3. 防抖处理 发送请求
      clearTimeout(timerId)
      timerId = setTimeout(() => {
        this.getEmployeeList()
      }, 500)
    },
    // 导出员工
    async exportEmployee() {
      const res = await exportEmployee()
      console.log(res) // blob数据
      // 使用file-saver保存下载数据
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 确认删除员工
    async confirm(id) {
      // console.log(id)
      // 1. 发送请求
      await delEmployee(id)
      // 2. 提示
      this.$message.success('删除成功')
      // page--
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      // 3. 重新渲染
      this.getEmployeeList()
    },
    // 展示为员工分配角色的对话框
    async showRoleDialog(id) {
      this.id = id // 存储员工id
      // 获取已启用的角色列表
      // const res = await getEnableRolesList()
      // this.rolesList = res.data
      // // 获取当前员工的详情信息中的roleIds  赋值给checkList
      // const { data: { roleIds }} = await getEmployeeDetail(id)
      // this.checkList = roleIds
      // 如何以最快的速度 拿到多个并发请求的结果 Promise.all
      Promise.all([getEnableRolesList(), getEmployeeDetail(id)]).then((vals) => {
        // console.log(vals)
        this.rolesList = vals[0].data
        this.checkList = vals[1].data.roleIds
        this.showRoleVisible = true
      })
    },
    // 为员工分配角色
    async submit() {
      // 1. 发送为员工分配角色的请求
      await assignRole({ id: this.id, roleIds: this.checkList })
      // 2. 提示
      this.$message.success('分配角色成功')
      // 3. 关闭对话框
      this.showRoleVisible = false
    }
  }
}

</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__wrap{
  overflow-x: hidden;
}
::v-deep .is-horizontal{
  height: 0;
}
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
